import backend from "app/backend";
import message from "app/messages";
import { getUrlVars } from "app/utils.js"

const query = getUrlVars();
document.title=query.title?decodeURIComponent(query.title):"换享";


$("#conv").attr('href', "/conversations/?token="+query.token+"&title="+query.title);
let myUID=-1;
let otherParty, me;
let container = $("#container");

async function loadMore() {
    container.scroll();
    let pulled = await message.pullConversation(query.otherParty);
    for (let msg of pulled) {
        addMessage(msg, myUID == msg.from ? me : otherParty, myUID == msg.from ? "right" : "left", true);
    }
    container.scroll(loadMore);
}

async function init() {
    await message.init(query.token);
    await message.clearConversationUnread(query.otherParty);
    myUID=await backend.tokenify(query.token);
    me = await backend.user.get(myUID);
    otherParty=await backend.user.get(query.otherParty);

    message.addMessageHandler((msg)=>{
        message.clearConversationUnread(query.otherParty);
        addMessage(msg, myUID==msg.from?me:otherParty, myUID==msg.from?"right":"left");
    });
    $("#mTitle").html("与"+otherParty.user_name+"的对话");

    loadMore();
    await message.clearConversationUnread(query.otherParty);

    if (typeof query.send !== "undefined"){
        let send=JSON.parse(decodeURIComponent(query.send));
        let result = await message.sendMessage(query.otherParty, send.messageType, send.messageContent);
        addMessage(result, me, "right");
    }
};
(init)();
//Scroll({ data: messages, pagesize: 5, callback: addMessage });

Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}


function addMessage(message, user, where, prepend) {
    let date=(message.time?new Date(message.time):new Date());
    let html = window[message.messageType + "_" + where]({user, message, msgTime:(date.Format("yyyy-MM-dd hh:mm:ss"))});
    if (prepend)
        container.prepend(html);
    else
        container.append(html);
    $(".tp-chat-main").scrollTop($("#container").outerHeight());
}

$(function () {
    $("#send").click(async function () {
        var msgVal = $("#text").val();
        if (msgVal.trim() == '') {
            layer.open({
                content: '不能发送空的消息！',
                skin: 'msg',
                time: 3
            });
            return;
        }
        let result = await message.sendMessage(query.otherParty, "text", msgVal);
        if (result.mid > 0) {
            $('#text').val('').focus();
            if (result.to == result.from) return;
            addMessage(result, me, "right");
        } else {
            console.log("sendMessage failed");
        }
    });

    document.onkeydown = function (event) {
        var e = event || window.event || arguments.callee.caller.arguments[0];
        if (e && e.keyCode == 13) { // enter 键
            $("#send").click();
        }
    };

});